import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, setToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import { ConstantNodeDependencies } from 'mathjs'
import { getTokenByTempToken } from '@/api/user'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist
function handleKeepAlive(to) {
  if (to.matched && to.matched.length > 2) {
    for (let i = 0; i < to.matched.length; i++) {
      const element = to.matched[i]
      if (element.components.default.name === 'EmptyView') {
        to.matched.splice(i, 1)
        handleKeepAlive(to)
      }
    }
  }
}
//路由守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // 从其他系统过来得token设置 由零时得token换取正式得token
  const urlToken = to.query.token
  if (urlToken) {
    const response = await getTokenByTempToken({ sessionId: urlToken })
    if (response.data) {
      setToken(response.data)
      location.replace(location.origin)
    }
  }
  // determine whether the user has logged in
  //const hasToken = getToken()

  // if (hasToken) {
  //   if (to.path === '/login') {
  //     // if is logged in, redirect to the home page
  //     next({ path: '/' })
  //     NProgress.done()
  //   } else {
  //     // determine whether the user has obtained his permission roles through getInfo
  //     const hasNames = store.getters.name
  //     if (hasNames) {
  //       next()
  //     } else {
  //       try {
  //         // await store.dispatch('user/getInfo')
  //         const { menus } = await store.dispatch('user/getInfo')
  //         const accessRoutes = await store.dispatch('permission/generateRoutes', menus)
  //         router.addRoutes(accessRoutes)
  //         // next({ ...to, replace: true })
  //         // await store.dispatch('permission/generateRoutes')
  //         next()
  //       } catch (error) {
  //         // remove token and go to login page to re-login
  //         await store.dispatch('user/resetToken')
  //         Message.error({
  //           message: error || 'Has Error'
  //         })
  //         next(`/login`)
  //         NProgress.done()
  //       }
  //     }
  //   }
  // } else {
  //   /* has no token */
  //   if (whiteList.indexOf(to.path) !== -1) {
  //     next()
  //   } else {
  //     next(`/login`)
  //     NProgress.done()
  //   }
  //   next()
  // }
  next()
})

router.afterEach((to, from) => {
  handleKeepAlive(to)
  NProgress.done()
})
